﻿
using housingsafety.server.Helpers;
using System;
using System.Security.Cryptography;
using System.Text;

namespace housingsafety.server.Security
{
    /// <summary>
    /// 加密
    /// </summary>
    public class WebAPISecret
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public WebAPISecret()
        {

        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="jwt"></param>
        /// <param name="secretKey"></param>
        /// <param name="uri"></param>
        public WebAPISecret(string userId, string jwt, string secretKey, string uri)
        {
            UserId = userId;
            SecretKey = secretKey;
            Timestamp = DateTime.UtcNow.Ticks;
            Uri = uri;
            Jwt = jwt;
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                var randomBytes = new byte[64];
                rngCryptoServiceProvider.GetBytes(randomBytes);
                NonceStr = UrlBase64.Encode(randomBytes, PaddingPolicy.Discard);
            }
        }

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="tk"></param>
        /// <param name="jwt"></param>
        /// <param name="secretKey"></param>
        /// <param name="uri"></param>
        public WebAPISecret(WebAPISign tk, string jwt, string secretKey, string uri)
        {
            UserId = tk.UserId;
            SecretKey = secretKey;
            Timestamp = tk.Timestamp;
            NonceStr = tk.NonceStr;
            Uri = uri;
            Jwt = jwt;
        }

        public string UserId { get; set; }
        public long Timestamp { get; set; }
        public string NonceStr { get; set; }
        public string Uri { get; set; }
        public string Jwt { get; set; }
        /// <summary>
        /// 该字段为保密字段，不要发送出来
        /// </summary>
        [System.Text.Json.Serialization.JsonIgnore]
        [Newtonsoft.Json.JsonIgnore]
        public string SecretKey { get; set; }

        /// <summary>
        /// 转为TOKEN
        /// </summary>
        /// <returns></returns>
        public WebAPISign ToSign()
        {
            return ToSign(this);
        }

        /// <summary>
        /// 转为TOKEN
        /// </summary>
        /// <param name="secret"></param>
        /// <returns></returns>
        public static WebAPISign ToSign(WebAPISecret secret)
        {
            var webApiSign = new WebAPISign();
            var originString = $"{secret.UserId}&{secret.Timestamp}&{secret.NonceStr}&{secret.Uri}&{secret.SecretKey}";

            webApiSign.UserId = secret.UserId;
            webApiSign.Timestamp = secret.Timestamp;
            webApiSign.NonceStr = secret.NonceStr;
            //所有字符转为大写
            webApiSign.Sign = originString.Sha256();
            webApiSign.JwtHash = secret.Jwt.Sha256();
            return webApiSign;
        }
    }
}
